#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 12 12:29:35 2019

@author: hyungmokson
"""

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon May 27 17:15:28 2019

@author: hyungmokson
"""
import matplotlib as mpl
from matplotlib import rcParams
mpl.use("pgf")
#from matplotlib.backends.backend_pgf import FigureCanvasPgf
#mpl.backend_bases.register_backend('pdf', FigureCanvasPgf)
#
print("MATPLOTLIB STUFF:")
print("matplotlib version: " + mpl.__version__)
print("matplotlib directory: " + mpl.__file__)
print(" ")
def figsize(scale):
    fig_width_pt = 350.                          # Get this from LaTeX using \the\textwidth
    inches_per_pt = 1.0/72.27                       # Convert pt to inch
    golden_mean = 0.8#(np.sqrt(5.0)-1.0)/2.0            # Aesthetic ratio (you could change this)
    fig_width = fig_width_pt*inches_per_pt*scale    # width in inches
    fig_height = fig_width*golden_mean              # height in inches
    fig_size = [fig_width,fig_height]
    return fig_size

#
pgf_with_latex = {                      # setup matplotlib to use latex for output
    "pgf.texsystem": "pdflatex",        # change this if using xetex or lautex
    "text.usetex": True,                # use LaTeX to write all text
#    "font.family": "serif",
#    "font.serif": [],                   # blank entries should cause plots to inherit fonts from the document
#    "font.sans-serif": [],
#    "font.monospace": [],
    "axes.linewidth": 1,
    "axes.labelsize": 7,               # LaTeX default is 10pt font.
#    "text.fontsize": 10,
    "legend.fontsize": 7,               # Make the legend/label fonts a little smaller
    "xtick.labelsize": 7,
    "ytick.labelsize": 7,
    "figure.figsize": figsize(0.9),     # default fig size of 0.9 textwidth
    "pgf.preamble": [
#        r"\usepackage[utf8x]{inputenc}",    # use utf8 fonts becasue your computer can handle it :)
#        r"\usepackage[T1]{fontenc}",
        r"\usepackage{amsmath}",
        r"\usepackage{amstext}", 
        r"\usepackage[utf8x]{inputenc}",
        r"\usepackage[T1]{fontenc}",
        r"\usepackage{cmbright}",# plots will be generated using this preamble
        ]
    }

pgf_with_latex_simple = {                      # setup matplotlib to use latex for output
    "pgf.texsystem": "pdflatex",        # change this if using xetex or lautex
    "text.usetex": True,
#    "font.family": "serif",
#    "font.serif": [],                   # blank entries should cause plots to inherit fonts from the document
#    "font.sans-serif": [],
#    "font.monospace": [],
    "axes.labelsize": 7,               # LaTeX default is 10pt font.
#    "text.fontsize": 10,
    "legend.fontsize": 7,               # Make the legend/label fonts a little smaller
    "xtick.labelsize": 7,
    "ytick.labelsize": 7              # use LaTeX to write all text]
    }
#
rcParams.update(pgf_with_latex)
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Arial']

import numpy as np
from numpy import linalg
import matplotlib.pyplot as plt
import os
from os import listdir
from os.path import isfile, join
from scipy.optimize import curve_fit


if __name__ == "__main__":
    working_dir = os.getcwd()
    sub = os.listdir(working_dir)
    print(working_dir)
    print(sub)
    
    main = working_dir
    plotpath = join(working_dir, 'plot save')
       
    def outputData(main, fileName, flg):
        if flg == 0:
            path = join(main, 'without Na')
        else:
            path = join(main, 'with Na')

        path = join(path, 'csv')
        name = str(fileName) + '.csv'
        temp = np.genfromtxt(join(path, name), delimiter=',', dtype=float, comments = "#", names=('var', 'data', 'err'))
        x = np.array(temp['var'])
        y = np.array(temp['data'])
        e = np.array(temp['err'])
        return x,y,e
 
           
    ## mol avg temp
    t_moltemp_avg_no, T_moltemp_avg_no, err_moltemp_avg_no = outputData(main, 'mol temp', 0)
    t_moltemp_avg, T_moltemp_avg, err_moltemp_avg = outputData(main, 'mol temp', 1)
    
    moltemp_no = []
    moltemp_no.append(t_moltemp_avg_no)
    moltemp_no.append(T_moltemp_avg_no)
    moltemp_no.append(err_moltemp_avg_no)
    
    moltemp = []
    moltemp.append(t_moltemp_avg)
    moltemp.append(T_moltemp_avg)
    moltemp.append(err_moltemp_avg)

    t_natemp_avg, T_natemp_avg, err_natemp_avg = outputData(main, 'na temp', 1)
    
    natemp = []
    natemp.append(t_natemp_avg)
    natemp.append(T_natemp_avg)
    natemp.append(err_natemp_avg)

    fig, ax = plt.subplots(1, 1, sharex=True, facecolor="white")
    hor = 8.9/2.54
    fig.set_size_inches(hor, hor * 4./6.)
    ax.tick_params(axis='both',  which='major')
    
#    lw = 1.2
    lw = 1.
#    ms = 5.65
    ms = 3.8
    fmt_list = ['o', 's', 'x']
    facecolor_list = ['white','#ff0000', '#000000']
    color_list=['#0000ff','#ff0000', '#000000']
    
    
    toPlot = []
    toPlot.append(moltemp_no)
    toPlot.append(moltemp)
    toPlot.append(natemp)
    i = 0
    for data in toPlot:
        x = data[0]
        y = data[1]
        err = data[2]
        
        (_, caps, _) = ax.errorbar(x,y, yerr = err, fmt = fmt_list[i], mew=lw, capsize=0, markersize=ms, c = color_list[i], markerfacecolor = facecolor_list[i]) ##
#        ax.grid(which='both', linestyle='dotted')

        i += 1
    
    for cap in caps:
    #cap.set_color('red')
        cap.set_markeredgewidth(0.)


    ##### plot avg temps    
    ax.legend(['NaLi without Na', 'NaLi with Na', 'Na'], loc='upper right', handlelength = 1.0, frameon = True, labelspacing = 0.2, facecolor = 'w', borderpad = 0.25, edgecolor ='w',  fontsize = 7, framealpha = 0., markerscale = 1)
    ylabel = "Temperature " + str(r"$(\mu\mathrm{K})$")
    plt.ylabel(ylabel)
    plt.xlabel(" Hold time (ms) ")
    plt.ylim([1.35, 2.48])
     
    ax.yaxis.set_ticks_position('both')
    ax.xaxis.set_ticks_position('both')
    ax.tick_params(direction='in')  
        
    plt.savefig(join(plotpath, "heating_avg.pdf"), bbox_inches='tight', pad_inches=0.01)  
    plt.show()   
    
#    def weightedAvgStd(data, err):
#        temp = data * (err**-2)
#        norm_factor = np.sum((err**-2))
#        avg = np.sum(temp)/norm_factor
#        std = 1./np.sqrt(norm_factor)
#        return avg, std
#    
    def weightedAvgStd(data, err):
        avg = np.average(data)
        stat_err = np.std(data)/np.sqrt(len(data)-1)
        uncert_err = np.sqrt(np.sum(err**2))/len(err)
        std = np.sqrt(stat_err**2 + uncert_err**2)
        return avg, std

    avg1, std1 = weightedAvgStd(T_natemp_avg, err_natemp_avg)
    print("")
    print("Heated Na average temp = " + str(avg1) + " / " + str(std1))
    
    avg, std = weightedAvgStd(T_moltemp_avg_no, err_moltemp_avg_no)
    print("")
    print("Mol without Na weighted average temp = " + str(avg) + " / " + str(std))
    